package com.gjp.config;

import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Created by gjp on 2017-6-2.
 */
@Configuration
@MapperScan("com.gjp.mapper*")
public class MybatisPlusConfig {

    //数据源
    @Autowired
    private DataSource dataSource;

    //插件拦截器
    @Autowired(required = false)
    private Interceptor[] interceptors;

    /**
     * mybatisplus总配置文件
     * @return
     */
    @Bean
    public MybatisSqlSessionFactoryBean sqlSessionFactory(){
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        //设置全局策略，词句不加，则下面的GlobalConfiguration就不起作用
        sqlSessionFactory.setGlobalConfig(globalConfiguration());
        //配置数据源,yml文件里的默认数据源
        sqlSessionFactory.setDataSource(dataSource);
        //设置插件拦截器,如果不配置此项，分页插件等类似功能则不起作用
        sqlSessionFactory.setPlugins(this.interceptors);
        return sqlSessionFactory;
    }

    /**
     * 全局策略
     */
    @Bean
    public GlobalConfiguration globalConfiguration() {
        GlobalConfiguration globalConfiguration = new GlobalConfiguration();
       /* 主键策略配置
        可选参数
        AUTO(0, "数据库ID自增"),
        INPUT(1, "用户输入ID"),
        ID_WORKER(2, "全局唯一ID"),
        UUID(3, "全局唯一ID"),
        NONE(4, "该类型为未设置主键类型");*/
        globalConfiguration.setIdType(IdType.AUTO.getKey());
       /* 数据库类型配置
        可选参数（默认mysql）
        MYSQL ->`mysql`
        ORACLE ->`oracle`
        DB2 ->`db2`
        H2 ->`h2`
        HSQL ->`hsql`
        SQLITE ->`sqlite`
        POSTGRE ->`postgresql`
        SQLSERVER2005 ->`sqlserver2005`
        SQLSERVER ->`sqlserver`*/
        //globalConfiguration.setDbType();
        return globalConfiguration;
    }

    /**
     * mybatis-plus分页插件<br>
     * 文档：http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setDialectType(DBType.MYSQL.getDb());
        return paginationInterceptor;
    }
}
